package com.example.lexiangbackend.controller;

import com.example.lexiangbackend.entity.User;
import com.example.lexiangbackend.entity.Music;
import com.example.lexiangbackend.entity.PlayHistory;
import com.example.lexiangbackend.entity.Favorite;
import com.example.lexiangbackend.service.AuthService;
import com.example.lexiangbackend.service.UserService;
import com.example.lexiangbackend.dto.LoginRequest;
import com.example.lexiangbackend.dto.RegisterRequest;
import com.example.lexiangbackend.dto.PhoneLoginRequest;
import com.example.lexiangbackend.dto.BindPhoneRequest;
import com.example.lexiangbackend.dto.UpdateProfileRequest;
import com.example.lexiangbackend.dto.ChangePasswordRequest;
import com.example.lexiangbackend.dto.DeleteAccountRequest;
import com.example.lexiangbackend.dto.AuthResponse;
import com.example.lexiangbackend.dto.FavoriteResponse;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.util.Map;
import java.util.HashMap;
import org.springframework.http.HttpStatus;

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "http://localhost:8080")
public class UserController {

    @Autowired
    private AuthService authService;
    
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<AuthResponse> register(@Valid @RequestBody RegisterRequest request) {
        try {
            AuthResponse response = authService.registerUser(request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new AuthResponse(false, e.getMessage(), null, null, null));
        }
    }

    /**
     * 用户邮箱/用户名登录
     */
    @PostMapping("/login")
    public ResponseEntity<AuthResponse> login(@Valid @RequestBody LoginRequest request) {
        try {
            AuthResponse response = authService.authenticateUser(request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new AuthResponse(false, e.getMessage(), null, null, null));
        }
    }

    /**
     * 用户手机号登录
     */
    @PostMapping("/login/phone")
    public ResponseEntity<AuthResponse> loginWithPhone(@Valid @RequestBody PhoneLoginRequest request) {
        try {
            AuthResponse response = authService.authenticateUserByPhone(request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new AuthResponse(false, e.getMessage(), null, null, null));
        }
    }

    /**
     * 发送手机验证码
     */
    @PostMapping("/send-code")
    public ResponseEntity<AuthResponse> sendVerificationCode(@RequestParam String phone) {
        try {
            AuthResponse response = authService.sendVerificationCode(phone);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new AuthResponse(false, e.getMessage(), null, null, null));
        }
    }

    /**
     * 用户个人资料
     */
    @GetMapping("/profile")
    public ResponseEntity<AuthResponse> getUserProfile(@RequestHeader("Authorization") String token) {
        try {
            // 提取token（移除Bearer前缀）
            String jwtToken = token.substring(7);
            User user = authService.verifyToken(jwtToken);
            return ResponseEntity.ok(new AuthResponse(true, "获取用户信息成功", jwtToken, "USER", user));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new AuthResponse(false, "获取用户信息失败", null, null, null));
        }
    }

    /**
     * 绑定手机号
     */
    @PostMapping("/bind-phone")
    public ResponseEntity<AuthResponse> bindPhone(@RequestHeader("Authorization") String token, 
                                                  @Valid @RequestBody BindPhoneRequest request) {
        try {
            // 提取token（移除Bearer前缀）
            String jwtToken = token.substring(7);
            AuthResponse response = authService.bindPhone(jwtToken, request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new AuthResponse(false, e.getMessage(), null, null, null));
        }
    }

    /**
     * 更新个人资料
     */
    @PostMapping("/update-profile")
    public ResponseEntity<AuthResponse> updateProfile(@RequestHeader("Authorization") String token,
                                                      @Valid @RequestBody UpdateProfileRequest request) {
        try {
            // 提取token（移除Bearer前缀）
            String jwtToken = token.substring(7);
            AuthResponse response = authService.updateProfile(jwtToken, request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new AuthResponse(false, e.getMessage(), null, null, null));
        }
    }

    /**
     * 修改密码
     */
    @PostMapping("/change-password")
    public ResponseEntity<AuthResponse> changePassword(@RequestHeader("Authorization") String token,
                                                       @Valid @RequestBody ChangePasswordRequest request) {
        try {
            // 提取token（移除Bearer前缀）
            String jwtToken = token.substring(7);
            AuthResponse response = authService.changePassword(jwtToken, request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new AuthResponse(false, e.getMessage(), null, null, null));
        }
    }

    /**
     * 注销账户
     */
    @PostMapping("/delete-account")
    public ResponseEntity<AuthResponse> deleteAccount(@RequestHeader("Authorization") String token,
                                                      @Valid @RequestBody DeleteAccountRequest request) {
        try {
            // 提取token（移除Bearer前缀）
            String jwtToken = token.substring(7);
            AuthResponse response = authService.deleteAccount(jwtToken, request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new AuthResponse(false, e.getMessage(), null, null, null));
        }
    }

    /**
     * 添加播放历史
     */
    @PostMapping("/play-history")
    public ResponseEntity<Map<String, Object>> addPlayHistory(@RequestHeader("Authorization") String token,
                                                              @RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            System.out.println("开始添加播放历史，请求数据: " + request);
            
            // 安全处理token
            if (token == null || !token.startsWith("Bearer ")) {
                System.err.println("无效的token格式: " + token);
                response.put("success", false);
                response.put("message", "无效的认证token格式");
                return ResponseEntity.badRequest().body(response);
            }
            
            String jwtToken = token.substring(7);
            System.out.println("提取的JWT token: " + jwtToken.substring(0, Math.min(20, jwtToken.length())) + "...");
            
            User user = authService.verifyToken(jwtToken);
            System.out.println("验证用户成功，用户ID: " + user.getUserId());
            
            if (request.get("musicId") == null) {
                System.err.println("musicId参数为空");
                response.put("success", false);
                response.put("message", "缺少musicId参数");
                return ResponseEntity.badRequest().body(response);
            }
            
            Long musicId = Long.valueOf(request.get("musicId").toString());
            System.out.println("准备添加播放历史，音乐ID: " + musicId);
            
            userService.addPlayHistory(user.getUserId(), musicId);
            System.out.println("添加播放历史成功");
            
            response.put("success", true);
            response.put("message", "播放历史添加成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("添加播放历史失败: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "添加播放历史失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取播放历史
     */
    @GetMapping("/play-history")
    public ResponseEntity<Map<String, Object>> getPlayHistory(@RequestHeader("Authorization") String token,
                                                             @RequestParam(defaultValue = "0") int page,
                                                             @RequestParam(defaultValue = "20") int size) {
        Map<String, Object> response = new HashMap<>();
        try {
            System.out.println("开始获取播放历史，page: " + page + ", size: " + size);
            
            // 安全处理token
            if (token == null || !token.startsWith("Bearer ")) {
                System.err.println("无效的token格式: " + token);
                response.put("success", false);
                response.put("message", "无效的认证token格式");
                return ResponseEntity.badRequest().body(response);
            }
            
            String jwtToken = token.substring(7);
            System.out.println("提取的JWT token: " + jwtToken.substring(0, Math.min(20, jwtToken.length())) + "...");
            
            User user = authService.verifyToken(jwtToken);
            System.out.println("验证用户成功，用户ID: " + user.getUserId());
            
            Pageable pageable = PageRequest.of(page, size);
            Page<PlayHistory> playHistoryPage = userService.getPlayHistory(user.getUserId(), pageable);
            
            System.out.println("查询播放历史成功，总记录数: " + playHistoryPage.getTotalElements());
            
            response.put("success", true);
            response.put("message", "获取播放历史成功");
            response.put("playHistory", playHistoryPage.getContent());
            response.put("totalElements", playHistoryPage.getTotalElements());
            response.put("totalPages", playHistoryPage.getTotalPages());
            response.put("currentPage", page);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("获取播放历史失败: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "获取播放历史失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 添加收藏
     */
    @PostMapping("/favorites")
    public ResponseEntity<Map<String, Object>> addFavorite(@RequestHeader("Authorization") String token,
                                                          @RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            System.out.println("开始添加收藏，请求数据: " + request);
            
            // 安全处理token
            if (token == null || !token.startsWith("Bearer ")) {
                System.err.println("无效的token格式: " + token);
                response.put("success", false);
                response.put("message", "无效的认证token格式");
                return ResponseEntity.badRequest().body(response);
            }
            
            String jwtToken = token.substring(7);
            System.out.println("提取的JWT token: " + jwtToken.substring(0, Math.min(20, jwtToken.length())) + "...");
            
            User user = authService.verifyToken(jwtToken);
            System.out.println("验证用户成功，用户ID: " + user.getUserId());
            
            if (request.get("musicId") == null) {
                System.err.println("musicId参数为空");
                response.put("success", false);
                response.put("message", "缺少musicId参数");
                return ResponseEntity.badRequest().body(response);
            }
            
            Long musicId = Long.valueOf(request.get("musicId").toString());
            System.out.println("准备添加收藏，音乐ID: " + musicId);
            
            userService.addFavorite(user.getUserId(), musicId);
            System.out.println("添加收藏成功");
            
            response.put("success", true);
            response.put("message", "收藏成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("添加收藏失败: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "收藏失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 取消收藏
     */
    @DeleteMapping("/favorites/{musicId}")
    public ResponseEntity<Map<String, Object>> removeFavorite(@RequestHeader("Authorization") String token,
                                                             @PathVariable Long musicId) {
        Map<String, Object> response = new HashMap<>();
        try {
            System.out.println("开始取消收藏，音乐ID: " + musicId);
            
            // 安全处理token
            if (token == null || !token.startsWith("Bearer ")) {
                System.err.println("无效的token格式: " + token);
                response.put("success", false);
                response.put("message", "无效的认证token格式");
                return ResponseEntity.badRequest().body(response);
            }
            
            String jwtToken = token.substring(7);
            System.out.println("提取的JWT token: " + jwtToken.substring(0, Math.min(20, jwtToken.length())) + "...");
            
            User user = authService.verifyToken(jwtToken);
            System.out.println("验证用户成功，用户ID: " + user.getUserId());
            
            userService.removeFavorite(user.getUserId(), musicId);
            System.out.println("取消收藏成功");
            
            response.put("success", true);
            response.put("message", "取消收藏成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("取消收藏失败: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "取消收藏失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取收藏列表
     */
    @GetMapping("/favorites")
    public ResponseEntity<Map<String, Object>> getFavorites(@RequestHeader("Authorization") String token,
                                                           @RequestParam(defaultValue = "0") int page,
                                                           @RequestParam(defaultValue = "20") int size) {
        Map<String, Object> response = new HashMap<>();
        try {
            System.out.println("开始获取收藏列表，page: " + page + ", size: " + size);
            
            // 安全处理token
            if (token == null || !token.startsWith("Bearer ")) {
                System.err.println("无效的token格式: " + token);
                response.put("success", false);
                response.put("message", "无效的认证token格式");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            String jwtToken = token.substring(7);
            System.out.println("提取的JWT token: " + jwtToken.substring(0, Math.min(20, jwtToken.length())) + "...");
            
            User user = authService.verifyToken(jwtToken);
            if (user == null) {
                System.err.println("Token验证失败，用户为null");
                response.put("success", false);
                response.put("message", "认证失败，请重新登录");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            System.out.println("验证用户成功，用户ID: " + user.getUserId());
            
            Pageable pageable = PageRequest.of(page, size);
            Page<Favorite> favoritePage = userService.getFavorites(user.getUserId(), pageable);
            
            System.out.println("查询收藏列表成功，总记录数: " + favoritePage.getTotalElements());
            
            // 转换为DTO
            List<FavoriteResponse> favoriteResponses = favoritePage.getContent()
                    .stream()
                    .map(FavoriteResponse::new)
                    .collect(Collectors.toList());
            
            response.put("success", true);
            response.put("message", "获取收藏列表成功");
            response.put("favorites", favoriteResponses);
            response.put("totalElements", favoritePage.getTotalElements());
            response.put("totalPages", favoritePage.getTotalPages());
            response.put("currentPage", page);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("获取收藏列表失败: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "获取收藏列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 检查收藏状态
     */
    @GetMapping("/favorites/check/{musicId}")
    public ResponseEntity<Map<String, Object>> checkFavoriteStatus(@RequestHeader("Authorization") String token,
                                                                   @PathVariable Long musicId) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 安全处理token
            if (token == null || !token.startsWith("Bearer ")) {
                response.put("success", false);
                response.put("message", "无效的认证token格式");
                return ResponseEntity.badRequest().body(response);
            }
            
            String jwtToken = token.substring(7);
            User user = authService.verifyToken(jwtToken);
            
            boolean isFavorite = userService.isFavorite(user.getUserId(), musicId);
            
            response.put("success", true);
            response.put("message", "检查收藏状态成功");
            response.put("isFavorite", isFavorite);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "检查收藏状态失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
} 